import axios from 'axios'
import {getToken} from '@/libs/util'
import store from '../store'

// import { Spin } from 'iview'
const addErrorLog = errorInfo => {
  // const { statusText, status, request: { responseURL } } = errorInfo
  // let info = {
  //   type: 'ajax',
  //   code: status,
  //   mes: statusText,
  //   url: responseURL
  // }
  //if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
}

class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }

  getHeader() {
    const token = getToken()
    if (!token) {
      return {}
    }
    return {
      'sports-user-token': token
    }
  }

  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: this.getHeader()
    }
    return config
  }

  destroy(url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }

  interceptors(instance, url) {
    
    // 请求拦截
    instance.interceptors.request.use(config => {
      
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      
      this.destroy(url)
      const {data, status} = res
      return {data, status}
    }, error => {
      
      this.destroy(url)
      let errorInfo = error.response
      console.log("返回：" + JSON.stringify(errorInfo))
      if (errorInfo && errorInfo.data && errorInfo.data.code == "401") {
        //此处直接刷新页面接口，因为beforeRouter那会进行判断。
        console.log("服务端返回401，调整到登录页面")
        location.reload()
        return
      }
      if (!errorInfo) {
        const {request: {statusText, status}, config} = JSON.parse(JSON.stringify(error))
        errorInfo = {
          statusText,
          status,
          request: {responseURL: config.url}
        }
      }
      addErrorLog(errorInfo)
      return Promise.reject(error)
    })
  }

  request(options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    
    return instance(options)
  }
}

export default HttpRequest
